package com.xunk.common.core.interceptor;

import com.xunk.common.core.utils.serialization.JsonSerializer;
import com.xunk.common.core.wrapper.ClientHttpResponseWrapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpMethod;
import org.springframework.http.HttpRequest;
import org.springframework.http.HttpStatus;
import org.springframework.http.client.ClientHttpRequestExecution;
import org.springframework.http.client.ClientHttpRequestInterceptor;
import org.springframework.http.client.ClientHttpResponse;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URI;
import java.nio.charset.StandardCharsets;

/**
 * @ProjectName: HIM
 * @Package: com.xunk.equipment.interceptor
 * @ClassName: LoggingClientHttpRequestInterceptor
 * @Author: luanzhiwei
 * @Description: 记录本服务使用resttemplate发出的请求日志和返回日志
 * @Date: 2021/4/27 9:31
 * @Version: 1.0
 */
//@Component
@Slf4j
public class LoggingClientHttpRequestInterceptor implements ClientHttpRequestInterceptor {


    @Override
    public ClientHttpResponse intercept(HttpRequest request, byte[] bytes, ClientHttpRequestExecution execution) throws IOException {
        //打印请求日志
        HttpMethod method = request.getMethod();
        URI uri = request.getURI();
        // 请求headers
        String requestHeaders = JsonSerializer.serialize(request.getHeaders());
        String query = uri.getQuery();
        String body = new String(bytes, StandardCharsets.UTF_8);
        log.info("Request-api Url：{},method: {} ,headers: {} ,requestParam: {} ,requestBody : {}", uri, method, requestHeaders, query, body);
        //开始时间
        long begin = System.currentTimeMillis();
        ClientHttpResponse response = execution.execute(request, bytes);
        long took = System.currentTimeMillis() - begin;
        ClientHttpResponse responseCopy = new ClientHttpResponseWrapper(response);

        //打印返回日志
        HttpStatus statusCode = responseCopy.getStatusCode();
        String responseHeaders = JsonSerializer.serialize(responseCopy.getHeaders());
        StringBuilder responseBody = new StringBuilder();
        try (BufferedReader bufferedReader =
                     new BufferedReader(new InputStreamReader(responseCopy.getBody(), StandardCharsets.UTF_8))) {
            String line = bufferedReader.readLine();
            while (line != null) {
                responseBody.append(line);
                // inputStringBuilder.append('\n');
                line = bufferedReader.readLine();
            }
        }
        log.info("Response-api  Url: {} ,status: {} ,headers: {} ,Response: {} ,took {} ms ", uri, statusCode, responseHeaders, responseBody, took);
        return responseCopy;
    }

}
